package jk.spider.core.storage.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import jk.spider.core.storage.SinfoDAO;
import jk.spider.model.Sinfo;

public class SinfoDAOImpl implements SinfoDAO {
	protected static final Logger log = Logger.getLogger(SinfoDAOImpl.class);
	protected DAOHelp daoHelp;
	
	public SinfoDAOImpl(DAOHelp daoHelp) {
		this.daoHelp = daoHelp;
	}
	
	public void create(Sinfo sinfo) {
		String sql = "insert into spider_sinfo (rid, desc, tag, recommend) values ("
					+ sinfo.getRid() + "," 
					+ daoHelp.format(sinfo.getDesc()) + "," 
					+ daoHelp.format(sinfo.getTag()) + ","
					+ daoHelp.format(sinfo.getRemd()) 
					+ ")";
		daoHelp.execSql(sql);
	}

	public Sinfo findById(int rid) {
		Sinfo sinfo = new Sinfo();
		ResultSet rs = null;
		Statement stmt = null;
		String sql = "select rid, desc, tag, recommend from spider_sinfo where rid = " + rid;
		try {
			stmt = daoHelp.getConnection().createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				sinfo.setDesc(rs.getString("desc"));
				sinfo.setTag(rs.getString("tag"));
				sinfo.setRemd(rs.getString("recommend"));
			}
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} catch (SQLException e) {
			log.error("SQLException -> ", e);
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} finally {
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		}
		return sinfo;
	}
	
	public void deleteAll() {
		String sql = "delete from spider_sinfo";
		daoHelp.execSql(sql);
	}
	
	public void create(String sid, String url) {
		String sql = "insert into sinfo_url (sid, url) values ("+ sid +", '"+ url +"')";
		daoHelp.execSql(sql);
	}
	
	public boolean isCrawlUrl(String url) {
		String sql = "select url from sinfo_url where url = '"+ url +"'";
		boolean having = false;
		ResultSet rs = null;
		Statement stmt = null;
		try {
			stmt = daoHelp.getConnection().createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				having = true;
			}
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} catch (SQLException e) {
			log.error("SQLException -> ", e);
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		} finally {
			daoHelp.safeClose(rs);
			daoHelp.safeClose(stmt);
		}
		return having;
	}

	public void deleteAllUrl() {
		String sql = "delete from sinfo_url";
		daoHelp.execSql(sql);
	}
}
